<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      :permission="permissionList"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad">
      <template #status="{row}">
        <el-tag v-if="row.status === 1" size="small" type='warning'>审核中</el-tag>
        <el-tag v-if="row.status === 2" size="small" type="success">审批通过</el-tag>
        <el-tag v-if="row.status === 3" size="small" type="danger">审批不通过</el-tag>
      </template>
      <template
        slot="infoForm"
        slot-scope="scope">
        <avue-crud :option="infoOption" :data="infoData">
        </avue-crud>
      </template>
      <template slot="menuLeft">
        <el-button
          type="primary"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="userInfo.role_name.includes('medical')"
          @click="handleImport">申请短缺药品
        </el-button>
      </template>
      <template slot-scope="scope" slot="menuForm" >
        <el-button v-if="userInfo.role_name.includes('districtAdmin')" type="info" size="small" icon="el-icon-close" @click.stop="handleEdits(form)">审批不通过</el-button>
        <el-button v-if="userInfo.role_name.includes('districtAdmin')" type="success" size="small" icon="el-icon-check" @click.stop="handleEdit(form)">审批通过</el-button>
      </template>
    </avue-crud>
    <el-dialog title="申请短缺药品" append-to-body :visible.sync="excelBox" width="555px">
      <avue-form :option="excelOption" v-model="excelForm" :upload-after="uploadAfter">
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate" plain>
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
<!--    <el-dialog title="区域管理员审批" append-to-body :visible.sync="excelBoxs" width="333px">-->
<!--      <avue-form :option="excelOptions" v-model="excelForm" >-->
<!--        <template slot="excelTemplate" slot-scope="scope">-->
<!--          <el-button type="primary" @click.stop="handleEdit(form)" >-->
<!--            审批通过<i class="el-icon-plus el-icon&#45;&#45;right"></i>-->
<!--          </el-button>-->
<!--        </template>-->
<!--        <template slot="excelTemplates" slot-scope="scope">-->
<!--          <el-button type="primary" @click="handleTemplate">-->
<!--            审批驳回<i class="el-icon-download el-icon&#45;&#45;right"></i>-->
<!--          </el-button>-->
<!--        </template>-->
<!--      </avue-form>-->
<!--    </el-dialog>-->
    <!--    <avue-crud :option="option"-->
    <!--               :table-loading="loading"-->
    <!--               :data="data"-->
    <!--               :page.sync="page"-->
    <!--               :permission="permissionList"-->
    <!--               :before-open="beforeOpen"-->
    <!--               v-model="form"-->
    <!--               ref="crud"-->
    <!--               @row-update="rowUpdate"-->
    <!--               @row-save="rowSave"-->
    <!--               @row-del="rowDel"-->
    <!--               @search-change="searchChange"-->
    <!--               @search-reset="searchReset"-->
    <!--               @selection-change="selectionChange"-->
    <!--               @current-change="currentChange"-->
    <!--               @size-change="sizeChange"-->
    <!--               @refresh-change="refreshChange"-->
    <!--               @on-load="onLoad">-->
    <!--      <template slot="menuLeft">-->
    <!--        <el-button type="danger"-->
    <!--                   size="small"-->
    <!--                   icon="el-icon-delete"-->
    <!--                   plain-->
    <!--                   v-if="permission.medicine_delete"-->
    <!--                   @click="handleDelete">删 除-->
    <!--        </el-button>-->
    <!--      </template>-->
    <!--    </avue-crud>-->
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove, examine } from "@/api/business/shortage";
import option from "@/const/business/shortage";
import {mapGetters} from "vuex";
import NProgress from "nprogress";
import {exportBlob} from "@/api/common";
import {getToken} from "@/util/auth";
import {downloadXls} from "@/util/util";
import {dateNow} from "@/util/date";
import color from "@/mixins/color";

export default {
  data() {
    return {
      excelBox: false,
      excelBoxs: false,
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        columnBtn:false,
        emptyBtn:false,
        dialogWidth:'70%',
        height: 'auto',
        calcHeight: 60,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        viewBtnText:"查看 / 审批",
        selection: false,
        dialogClickModal: false,
        searchShowBtn: true,
        searchIcon: true,
        searchIndex: 4,
        addBtn:false,
        delBtn:false,
        editBtn:false,
        labelWidth: 120,
        column: [
          {
            label: "区县",
            prop: "district",
            type: "select",
            cascader: ['instName'],
            dicUrl: "/api/blade-system/dict/dictionary?code=medpur_institution",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            search: true,
            rules: [{
              required: true,
              message: "请输入区县",
              trigger: "blur"
            }],
            searchSpan: 5,
          },
          {
            label: "医药机构名称",
            prop: "instName",
            type: "select",
            search: true,
            dicUrl: "/api/institution/lists?district={{key}}",
            filterable:true,
            props: {
              label: "instName",
              value: "instName"
            },
            searchLabelWidth: 120,
            searchSpan: 8,
            rules: [{
              required: true,
              message: "请输入",
              trigger: "blur"
            }],
          },
          {
            label: "申报时间",
            prop: "createTime",
            width: 150,
            type: "input",
          },
          {
            label: "城市",
            prop: "city",
            hide: true,
            type: "input",
            addDisplay: false,
            editDisplay: false,
          },
          {
            label: "审核状态",
            prop: "status",
            type: "radio",
            search: true,
            dicUrl: "/api/blade-system/dict/dictionary?code=offline_purchase_exa",
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            searchLabelWidth: 80,
            searchSpan: 5,
            rules: [{
              required: true,
              message: "请输入",
              trigger: "blur"
            }],
          },
          {
            labelWidth: 0,
            label: '',
            prop: 'info',
            span: 24,
            hide: true
          }
        ]
      },
      infoOption: {
        menu:false,
        border: true,
        column: [
          {
            label: '药品流水号',
            width:120,
            prop: 'medicineNo',
          },
          {
            label: '通用名',
            prop: 'medicineName',
            width:220,
            overHidden: true,
          },
          {
            label: '剂型',
            prop: 'shotType',
            overHidden: true,
          },
          {
            label: '规格',
            prop: 'specification',
            overHidden: true,
          },
          {
            label: '新版基药属性',
            prop: 'baseMedProp',
            width: 120,
            overHidden: true
          },
          {
            label: '采购金额',
            prop: 'purchaseFee',
            overHidden: true,
          },
          {
            label: '采购数量',
            prop: 'purchaseAmount',
            overHidden: true,
          },
          {
            label: '备注',
            prop: 'remark',
            overHidden: true,
          },
        ]
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '文件上传',
            prop: 'excelFile',
            type: 'upload',
            drag: true,
            loadText: '文件上传，请稍等',
            span: 24,
            showFileList: false,
            propsHttp: {
              res: 'data'
            },
            tip: '请上传 .xls,.xlsx 标准格式文件',
            action: "/api/blade-shortageItem/shortageItem/import-order"
          },
          // {
          //   label: "数据覆盖",
          //   prop: "isCovered",
          //   type: "switch",
          //   align: "center",
          //   width: 80,
          //   dicData: [
          //     {
          //       label: "否",
          //       value: 0
          //     },
          //     {
          //       label: "是",
          //       value: 1
          //     }
          //   ],
          //   value: 0,
          //   slot: true,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请选择是否覆盖",
          //       trigger: "blur"
          //     }
          //   ]
          // },
          {
            label: '模板下载',
            prop: 'excelTemplate',
            formslot: true,
            span: 24,
          }
        ]
      },
      excelOptions: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '',
            prop: 'excelTemplate',
            type: "input",
            formslot: true,
            span: 24,
          },
          {
            label: '',
            prop: 'excelTemplates',
            formslot: true,
            span: 24,
          }
        ]
      }
    };
  },
  created(){
    let district = this.findObject(this.option.column,'district');
    let instName = this.findObject(this.option.column,'instName');
    if(this.userInfo.role_name==="medical"){
      district.searchDisabled=true
      instName.searchDisabled=true
      district.searchValue=this.loginUserInfo.institution.district
      instName.searchValue=this.loginUserInfo.institution.instName
      this.$set(this.query,"instName",instName.searchValue)
      this.$set(this.query,"district",district.searchValue)
    }
    if(this.userInfo.role_name==="districtAdmin"){
      district.searchDisabled=true
      district.searchValue=this.loginUserInfo.dept.remark
      this.$set(this.query,"district",district.searchValue)
    }
  },
  computed: {
    ...mapGetters(["userInfo","permission","loginUserInfo"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.medicine_add, false),
        viewBtn: this.vaildData(this.permission.medicine_view, true),
        delBtn: this.vaildData(this.permission.medicine_delete, false),
        editBtn: this.vaildData(this.permission.medicine_edit, false)
      };
    },
    infoData(){
      return this.form.info
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    rowSave(row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    handleEdit(row) {
      this.$confirm("确认审批通过数据?", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "success"
      })
        .then(() => {
          row.status = 2
          return  examine(row);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$refs.crud.$refs.dialogForm.closeDialog()
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })
    },
    handleEdits(row) {
      this.$confirm("确认驳回此数据?", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "success"
      })
        .then(() => {
          row.status = 3
          return  examine(row);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$refs.crud.$refs.dialogForm.closeDialog();
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        })
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          console.log(res.data.data.shortageItemEntityList,"666")
          this.form.info = res.data.data.shortageItemEntityList;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage){
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize){
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleImportExl() {
      this.excelBoxs = true;
    },
    handleTemplate() {
      exportBlob(`/api/blade-shortageItem/shortageItem/export-template?${this.website.tokenHeader
      } = ${getToken()}`).then(res => {
        downloadXls(res.data, "短缺药品数据模板.xlsx");
      })
    },
    uploadAfter(res, done, loading, column) {
      try {
        console.log("upload res: ", res)
        if (!res) {
          this.$message.success("导入成功")
          this.excelBox = false;
          this.refreshChange();
        }
      } finally {
        done()
      }
    },
    auditStatusFormate(row) {
      if (row.status) {
        return row.status === '1'
          ? '有效'
          : row.status === '2'
            ? '未审核'
            : ''
      }
    },
  }
};
</script>

<style>
</style>
